package dj.common.constants;

import com.dj.common.exception.CentralRunException;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * <br>
 * <p>
 * -
 * </p>
 *
 * <br>
 *
 * @author ZJG
 * @version 1.0
 * @date 2021/12/1 下午5:55
 */
public interface EnumCustom extends Serializable {

    /**
     * enum alias
     * @return
     */
    String alias();

    Map<Class, Map> ENUM_MAP = new HashMap<>();

    static <E extends Enum & EnumCustom> E getByName(String name, Class<E> clazz) throws CentralRunException {
        Map enumMap = ENUM_MAP.get(clazz);

        if(null == enumMap) {
            E[] enums = clazz.getEnumConstants();

            enumMap = new HashMap<String, E>();

            for(E current : enums) {
                enumMap.put(current.alias(), current);
            }
        }

        E result =  (E) enumMap.get(name);
        if(result != null) {
            return result;
        } else {
            throw new CentralRunException("No element matches " + name);
        }
    }

}
